<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreHonorRequest;
use App\Http\Requests\UpdateHonorRequest;
use App\Http\Resources\ServiceResource;
use App\Models\Honor;
use Illuminate\Http\Request;

class HonorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name = $request->name ?? '';
        $per_page = $request->per_page ?? 10;
        $sort = json_decode($request->sort, true);

        $resource = Honor::when($name, function ($query) use ($name) {
            return $query->where('name', 'like', "%$name%");
        })->when($sort, function ($query) use ($sort) {
            foreach ($sort as $item) {
                $val = str_replace('end', '', $item['order']);
                $query->orderBy($item['field'], $val);
            }
        }, function ($query) {
            return $query->orderBy('id', 'desc');
        })->paginate($per_page);
        return new ServiceResource($resource);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreHonorRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreHonorRequest $request)
    {
        return $this->successful(Honor::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Honor  $honor
     * @return \Illuminate\Http\Response
     */
    public function show(Honor $honor)
    {
        return $this->successful($honor);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateHonorRequest  $request
     * @param  \App\Models\Honor  $honor
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateHonorRequest $request, Honor $honor)
    {
        return $this->successful($honor->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Honor  $honor
     * @return \Illuminate\Http\Response
     */
    public function destroy(Honor $honor)
    {
        $honor->delete();
        return $this->successful();
    }

    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->fail(400, 'ids is required');
        }
        Honor::whereIn('id', $ids)->delete();
        return $this->successful($ids);
    }
}
